﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Morus.Presentation
{
    internal static class TypeExtension
    {
        static readonly ConcurrentDictionary<RuntimeTypeHandle, IEnumerable<Type>> _implementationTypeToViewInterfacesCache = new ConcurrentDictionary<RuntimeTypeHandle, IEnumerable<Type>>();

        [DebuggerStepThrough]
        internal static IEnumerable<Type> GetViewInterfaces(this Type implementationType)
        {
            // We use the type handle as the cache key because they're fast
            // to search against in dictionaries.
            var implementationTypeHandle = implementationType.TypeHandle;

            return _implementationTypeToViewInterfacesCache.GetOrAdd(implementationTypeHandle, (t) =>
                implementationType
                    .GetInterfaces()
                    .Where(typeof(IView).IsAssignableFrom)
                    .ToArray()
            );
        }
    }
}